package com.zmn.oms.zmn.normal.business.impl.work;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.oms.business.interfaces.orderstock.OrderStockBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderTagConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.dto.tag.OrderTagDTO;
import com.zmn.oms.model.dto.work.modify.OrderWorkTagDTO;
import com.zmn.oms.model.entity.conf.ordertag.ConfOrderTag;
import com.zmn.oms.model.entity.conf.ordertag.ConfOrderTagQuery;
import com.zmn.oms.model.entity.tag.OrderTag;
import com.zmn.oms.model.vo.work.modify.OrderTagVO;
import com.zmn.oms.services.interfaces.conf.ordertag.ConfOrderTagService;
import com.zmn.oms.services.interfaces.tag.OrderTagService;
import com.zmn.oms.zmn.normal.business.interfaces.work.OrderWorkTagBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类描述：工单标签标记接口
 *
 * @author liuying
 * @date 2021/08/19 13:48
 */
@Slf4j
@Service
public class OrderWorkTagBServiceImpl implements OrderWorkTagBService {

    @Autowired
    private OrderTagService orderTagService;
    @Autowired
    private ConfOrderTagService confOrderTagService;
    @Autowired
    private OrderStockBService orderStockBService;

    @Override
    public OrderTagVO getOrderTagVO(Long orderId, Long workId) {
        OrderTagVO orderTagVO = new OrderTagVO();
        orderTagVO.setOrderId(orderId);
        orderTagVO.setWorkId(workId);

        // 处理选中的tag
        List<OrderTag> orderTags = orderTagService.listOrderTagByOrderId(orderId, workId);
        List<Integer> tagIds = orderTags.stream().map(OrderTag::getTagId).collect(Collectors.toList());

        ConfOrderTagQuery query = ConfOrderTagQuery.builder().status(GlobalConsts.YES).minId(1000).build();
        List<ConfOrderTag> tags = confOrderTagService.listByQuery(query);

        List<KVDict<Integer>> tagList = Lists.newArrayListWithCapacity(tags.size());
        tags.stream().sorted(Comparator.comparing(ConfOrderTag::getId)).forEach(e -> {
            KVDict<Integer> tagDict = KVDict.<Integer>builder()
                    .value(e.getId())
                    .text(e.getTagName())
                    .ext1(e.getTagShortName()).build();
            if (tagIds.contains(e.getId())) {
                tagDict.setSelected(true);
                tagDict.setDisabled(true);
            }
            tagList.add(tagDict);
        });

        orderTagVO.setTagList(tagList);

        return orderTagVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_ORDER_WORK_TAG, beforeProceed = false)
    public void saveOrderTag(OrderWorkTagDTO orderWorkTagDTO) throws OmsBaseException {
        if (CollectionUtil.isNullOrEmpty(orderWorkTagDTO.getTags())) {
            return;
        }

        // 标记配置
        List<ConfOrderTag> confOrderTagList = confOrderTagService.listByQuery(ConfOrderTagQuery.builder().build());
        Map<Integer, ConfOrderTag> confOrderTagMap = confOrderTagList.stream().collect(Collectors.toMap(ConfOrderTag::getId, item -> item, (k1, k2) -> k1));

        // 添加新的标签
        List<OrderTag> tags = orderWorkTagDTO.getTags();
        Long orderId = orderWorkTagDTO.getOrderId();
        Long workId = orderWorkTagDTO.getWorkId();

        List<OrderTag> orderTagList = tags.stream().filter(item -> confOrderTagMap.containsKey(item.getTagId()))
                .map(tag -> {
                    ConfOrderTag confOrderTag = confOrderTagMap.get(tag.getTagId());
                    tag.setOrderId(orderId);
                    tag.setWorkId(workId);
                    tag.setTagName(confOrderTag.getTagName());
                    tag.setCategoryIds(confOrderTag.getCategoryIds());
                    tag.setTagType(OrderTagConsts.ORDER_TAG_USER_STAFF);
                    tag.setCreater(orderWorkTagDTO.getOperator());
                    tag.setUpdater(orderWorkTagDTO.getOperator());
                    return tag;
                }).collect(Collectors.toList());

        OrderTagDTO orderTagDTO = new OrderTagDTO();
        orderTagDTO.setOrderId(orderId);
        orderTagDTO.setWorkId(workId);
        orderTagDTO.setOrderTagList(orderTagList);
        orderTagService.saveOrderTagList(orderTagDTO);

        // 竞争工单 释放库存
        List<Integer> tagIdList = orderWorkTagDTO.getTags()
                .stream()
                .map(OrderTag::getTagId)
                .collect(Collectors.toList());
        if (tagIdList.contains(OrderTagConsts.TAG_ID_WORK_COMPETITION)) {
            orderStockBService.releaseStock(orderWorkTagDTO.getOrderId(), orderWorkTagDTO.getWorkId());
        }
    }
}
